import path from 'path'

import passport from 'passport'
import passport_local from 'passport-local';

import bodyParser from 'body-parser';
import badger, {log, badgerAuth} from '@codefree/badger/service'
import {parseAuthToken} from './app/utility/helper'

const nodeEnv = process.env.NODE_ENV || 'dev';
const config = require(path.normalize(__dirname + '/config/config.' + nodeEnv + ".js"));

const badgerApp = new badger(config);
const app = badgerApp.createApplication((expressApp) => {
    // 当前方法内的逻辑会在路由初始化之前执行

    expressApp.use(bodyParser.urlencoded({extended: true, limit: '10mb'}));
    expressApp.use(bodyParser.json());

    expressApp.use((req, res, next) => {
        res.header("Access-Control-Allow-Origin", "*");
        res.header("access-control-allow-methods", "GET, POST");
        res.header("Access-Control-Expose-Headers", config.authTokenName);
        res.header("Access-Control-Allow-Headers", `Origin,X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept, ${config.authTokenName}`);
        next();
    });

    expressApp.use(passport.initialize());
    expressApp.use(passport.authenticate('jwt', {session: false}));
    passport.use(
        new badgerAuth.strategies.jwtStrategy({tokenHeader: config.authTokenName}, function (token, done) {
            let userInfo = parseAuthToken(token);
            if (!userInfo) {
                return done(null, false)
            }

            return done(null, userInfo)
        }));

    passport.use(new passport_local.Strategy(
        (username, password, done) => {
            badgerApp.context.serviceLoader.service["auth"].login({
                username, password
            })
                .then((user) => {
                    if (!user) {
                        done(null, false);
                    } else {
                        done(null, user);
                    }
                })
                .catch((err) => {
                    done(err)
                })
        }
    ));
});

const logger = log.getLogger();

if (nodeEnv === "dev") {
    // request log
    const morgan = require('morgan');
    // // node app monitor
    // const easyMonitor = require('easy-monitor');
    // easyMonitor('project-template');
    app.use(morgan('dev'));
}

app.listen(config.port || 3000);

logger.info(`${config.systemName} listening at port ${config.port || 3000}`);